# -*- coding: utf-8 -*-

import datetime

from app.utils import safe_int
from app.constants import MTU_TYPE


def get_product_infos(products, device_id=''):
    """
    获取旅行产品的信息(包括酒店)
    """

    from app.models import Mtu

    items = []
    # products = []
    # for product in products:
    #     #判断是否有酒店产品
    #     if not isinstance(product, dict):
    #         product_list.append(product)

    # print 'products', products
    # skus = ProductSKU.objects(product__in=products)
    #         productskus
    # print 'skus', skus
    # mtus = Mtu.objects(target_type=MTU_TYPE.PRODUCT,
    #                    target_id__in=[x.id for x in products])
    # destinations = Destination.objects(
    # pk__in=set(x.destination.id for x in products))
    for product in products:
        if False:
            # FIXME: 如果是酒店
            pass
        else:
            # if not mtus.filter(target_id=str(product.pk)):
            #     continue
            # mtu = mtus.get(target_id=product.pk)
            mtu = Mtu.objects(target_type=MTU_TYPE.PRODUCT, target_id=str(product.pk)).first()
            # print 'mtu', mtu, 'target_id', product.pk
            if not mtu:
                continue
            # destination = destinations.get(pk=product.destination)
            retail_fee = 0
            if product.productskus:
                # sku = ProductSKU.objects(pk__in=product.productskus, is_default=True).first()
                for sku in product.productskus:
                    if sku.is_default is True:
                        break
                retail_fee = sku.adult_retail_fee
            website = ''
            # if product.template_id == 6:
            #     website = '%sspecial/product/%s/detail/?device_id=%s' % (
            #             settings.BASE_VACATION_URL, product.pk, device_id)
            #     product.category_id = 16
            # if product.template_id == 5:
            #     product.category_id = 7

            # 产品分类(标签筛选)
            if product.classify:
                category_name = product.classify.name
            else:
                category_name = ''
            items.append({
                'name': '%s' % (product.name),
                'region': product.destination.name,
                'cover': product.cover,
                'fee': safe_int(product.fee),
                'retail_fee': safe_int(retail_fee),
                'id': str(product.pk),
                'category_id': product.category_id,
                'category_name': category_name,
                'website': website,
                'mtu_id': str(mtu.pk),
                'mtu_type': mtu.target_type,
            })

    return items


def get_productsku_blackout_date(skus, start=None, book_date=None):
    """
    获取产品的不可预定日期
    args:
    ~~~~~~~~~~~~~~~~
    start: 从start日期开始计算，往后的43天是否可预定
    book_date: 当这个日期存在，返回boolean，提示这天是否可用
    """
    from app.models import Product
    if not start and not book_date:
        raise Exception("start and book_date must have one")

    product_ids = set(str(x.product.id) for x in skus)
    if len(product_ids) > 1:
        raise Exception("it's return more than one product")

    product = Product.objects(pk=list(product_ids)[0]).first()
    today = datetime.date.today()
    now = datetime.datetime.now().strftime('%H:%M')

    # 产品起订和截止日期
    k = 1 if product.start_time and \
        now > product.start_time else 0
    if safe_int(product.start_delta):
        k += safe_int(product.start_delta)
    start_date = today + datetime.timedelta(days=k)
    end_date = product.close_date and product.close_date.date()
    if book_date and (book_date < start_date or
                      (end_date and book_date > end_date)):
        return False

    # 产品类型 起订和截止日期
    week_binary = list('1111111')
    for sku in skus:
        # print 'sku', sku.end_date, type(sku.end_date), type(sku.end_date.date()), type(end_date), end_date
        sku.end_date.date() < end_date
        _binary = ('000000%s' % safe_int(sku.week_binary))[-7:]
        if sku.start_date and sku.start_date.date() > start_date:
            start_date = sku.start_date
        if (not end_date and sku.end_date) or \
                (end_date and sku.end_date and sku.end_date.date() < end_date):
            end_date = sku.end_date.date()
        for k, v in enumerate(week_binary):
            week_binary[k] = '1' if int(v) and int(_binary[k]) else '0'
    week_binary = ''.join(week_binary)
    if book_date and (book_date < start_date or (end_date and book_date > end_date)
                      or not int(week_binary[book_date.weekday()])):
        return False

    # 类型不可预定日期
    blackouts = set()
    map(blackouts.update, [x.blackoutdate for x in skus])
    if book_date:
        return book_date not in blackouts

    result = []
    for i in xrange(43):
        date = start + datetime.timedelta(days=i)
        item = {'start': str(date), 'date': str(date)}
        j = date.weekday()
        # print 'week_binary', week_binary, date, week_binary[j], 'date', date, 'start_date', start_date, 'end_date', end_date#, 'blackouts', blackouts
        # print date < start_date, date > end_date
        if not int(week_binary[j]) or (date < start_date) or \
                (end_date and (date > end_date)) or (date in blackouts):
            item['title'] = str(date)
        else:
            item['title'] = ''
        result.append(item)
    return result
